/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GoLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_01_01			*/
/*	File:		GoTcp.go			*/
/********************************************************/

package GoNet

import (
	"net"
)

const (
	GO_TP_TCPA	string = "tcp"
	GO_TP_TCP4	string = "tcp4"
	GO_TP_TCP6	string = "tcp6"
)

/* addr */
type GoTcpAdd struct {
	add	*net.TCPAddr
}

func (t *GoTcpAdd) __TcpAddr(n string, a string) (err error) {
	t.add, err = net.ResolveTCPAddr(n, a)
	return err
}

/* conn */
type GoTcpCon struct {
	con	*net.TCPConn
}

func (c *GoTcpCon) GoTcpConClose() {
	c.con.Close()
}

func (n *GoTcpCon) GoTcpConGet() *net.TCPConn {
	return n.con
}

func (n *GoTcpCon) GoTcpConPut(c *net.TCPConn) {
	n.con = c
}

func (n *GoTcpCon) GoTcpConRead(b []byte) (int, error) {
	return n.con.Read(b)
}

func (n *GoTcpCon) GoTcpConWrite(b []byte) (int, error) {
	return n.con.Write(b)
}

/* client */
type GoTcpCli struct {
	ad	GoTcpAdd
	cn	GoTcpCon
}

func (c *GoTcpCli) GoTcpCliClose() {
	c.cn.con.Close()
}

func (c *GoTcpCli) GoTcpCliAddr() *net.TCPAddr {
	return c.ad.add
}

func (c *GoTcpCli) GoTcpCliConn() *net.TCPConn {
	return c.cn.con
}

func (c *GoTcpCli) GoTcpCliRead(b []byte) (int, error) {
	return c.cn.GoTcpConRead(b)
}

func (c *GoTcpCli) GoTcpCliWrite(b []byte) (int, error) {
	return c.cn.GoTcpConWrite(b)
}

func (c *GoTcpCli) GoTcpCliDial(n string, a string) (err error) {
	if nil == c.ad.__TcpAddr(n, a) {
		c.cn.con, err = net.DialTCP(n, nil, c.ad.add)
	}
	return err
}

/* server */
type GoTcpSer struct {
	ad	GoTcpAdd
	cn	*net.TCPListener
}

func (s *GoTcpSer) GoTcpSerClose() {
	s.cn.Close()
}

func (s *GoTcpSer) GoTcpSerAddr() *net.TCPAddr {
	return s.ad.add
}

func (s *GoTcpSer) GoTcpSerConn() *net.TCPListener {
	return s.cn
}

func (s *GoTcpSer) GoTcpSerAccept() (*net.TCPConn, error) {
	return s.cn.AcceptTCP()
}

func (s *GoTcpSer) GoTcpSerListen(n string, a string) (err error) {
	if nil == s.ad.__TcpAddr(n, a) {
		s.cn, err = net.ListenTCP(n, s.ad.add)
	}
	return err
}
